package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.BasicDoc;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.consignor.CustomerCarModel;
import com.example.chcrm.entity.consignor.CustomerInfo;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.employee.EssEmployee;
import com.example.chcrm.entity.employee.RoleModels;
import com.example.chcrm.entity.vehicle.TransportChildCv;
import com.example.chcrm.entity.vehicle.TransportPlanCv;
import com.example.chcrm.mapper.CustomerInfoMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.mapper.TransportChildCvMapper;
import com.example.chcrm.mapper.TransportPlanCvMapper;
import com.example.chcrm.service.TransportPlanCvService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/4/24 11:11
 * @Version 1.0
 */
@Service
public class TransportPlanCvServiceImpl<T> implements TransportPlanCvService {
    @Autowired
    TransportPlanCvMapper transportPlanMapper;
    @Autowired
    TransportChildCvMapper transportChildCvMapper;
    @Autowired
    OperateRecordMapper operateRecordMapper;
    @Autowired
    CustomerInfoMapper customerInfoMapper;

    @Override
    public ResponseMsg<IPage<TransportPlanCv>> pageList(TransportPlanCv tpc) {
        QueryWrapper<TransportPlanCv> query = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("YYY-MM-dd");
        if (StringUtils.isNotBlank(tpc.getConsignorName())) {
            query.like("consignor_name", tpc.getConsignorName());
        }
        if (StringUtils.isNotBlank(tpc.getBatchNumber())) {
            query.like("batch_number", tpc.getBatchNumber());
        }
        if (tpc.getTransportMode() != null) {
            query.like("transport_mode", tpc.getTransportMode());
        }
        if (tpc.getStartTime() != null) {
            query.ge("create_time", tpc.getStartTime());
        }
        if (tpc.getEndTime() != null) {
            query.le("DATE_FORMAT(create_time,'%Y-%m-%d')", sdf.format(tpc.getEndTime()));
        }
        query.eq("is_deleted", BasicDoc.NOT_DELETE);
        query.orderByDesc("create_time");

//        Page<TransportPlanCv> page = new Page<>(tpc.getPage(), tpc.getRows());

        List<TransportPlanCv> list = transportPlanMapper.selectList(null,query);
//        List<TransportPlanCv> records = transportPlanCvPage.getRecords();
        if (list.size()>0){
            for (TransportPlanCv record : list) {
                QueryWrapper<TransportChildCv> tcv =new QueryWrapper<>();
                tcv.eq("basic_id",record.getId());
                tcv.eq("state",3);
                Integer integer = transportChildCvMapper.selectCount(tcv).intValue();
                if (integer>0){
                    //如果有1辆车交车了就是1，没有则是0
                    record.setStatus(1);
                }

            }
        }

//        return transportPlanCvPage;
        ResponseMsg<IPage<TransportPlanCv>> iPageResponseMsg = new ResponseMsg<>();
//        List<TransportPlanCv> list = transportPlanCvMapper.pageList(transportPlanCv);
        Page<TransportPlanCv> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(tpc.getRows());
        page.setCurrent(tpc.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    public ResponseMsg<Object> add(TransportPlanCv tpc, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        String uuid = RandomHelper.uuid();
        int numP = transportPlanMapper.selectCount(new QueryWrapper<TransportPlanCv>()
                .eq("batch_number", tpc.getBatchNumber())
                .eq("is_deleted", BasicDoc.NOT_DELETE)).intValue();
        if (numP > 0) {
            msg.fail("添加失败，批次号已存在");
            return msg;
        }
        if (StringUtils.isBlank(tpc.getConsignorName())){
            msg.fail("添加失败，委托商不存在");
            return msg;
        }
        CustomerInfo consignor = customerInfoMapper.selectOne(new QueryWrapper<CustomerInfo>()
                .eq("customer_name",tpc.getConsignorName()));
        tpc.setId(uuid);
        tpc.setConsignorId(consignor.getId());
        tpc.setPlanNumber(getTransportPlanCode());
        tpc.setLeftoverPlanCount(0);
        tpc.setState(0);
        tpc.setCreateTime(new Date());
        transportPlanMapper.insert(tpc);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_ADD);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
//        ope.setOperationId(empVo.getId());
        ope.setSourceId(uuid);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
//        ope.setOperationName(empVo.getEmpNm());
        operateRecordMapper.insert(ope);
        msg.success("添加成功");
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        TransportPlanCv transportPlan = transportPlanMapper.selectOne(new QueryWrapper<TransportPlanCv>()
                .eq("is_deleted", BasicDoc.NOT_DELETE)
                .eq("id", id));
        if (transportPlan == null) {
            msg.fail("查询失败，数据不存在");
            return msg;
        }
        //查询委托车列表
        List<TransportChildCv> childList = transportChildCvMapper.selectList(new QueryWrapper<TransportChildCv>()
                .eq("basic_id", transportPlan.getId())
                .eq("is_deleted", BasicDoc.NOT_DELETE));
        transportPlan.setTransportChildCvList(childList);
        //查询操作日志
        QueryWrapper<OperateRecord> opQuery = new QueryWrapper<>();
        opQuery.eq("sourceId", id).orderByDesc("create_time");
        List<OperateRecord> operateRecordList = operateRecordMapper.selectList(opQuery);
        transportPlan.setOperateRecordList(operateRecordList);
        msg.setData(transportPlan);
        msg.success("查询成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(TransportPlanCv transportPlanCv, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        // 参数基础校验
        if (StringUtils.isBlank(transportPlanCv.getId())) {
             msg.fail("运输计划ID不能为空");
            return msg;
        }
        if (StringUtils.isBlank(transportPlanCv.getConsignorName())) {
            msg.fail("委托商名称不能为空");
            return msg;
        }
        if (StringUtils.isBlank(transportPlanCv.getBatchNumber())) {
            msg.fail("批次号不能为空");
            return msg;
        }
        if (transportPlanCv.getPlanCount() == null || transportPlanCv.getPlanCount() <= 0) {
            msg.fail("委托车数量必须大于0");
            return msg;
        }

        // 查询原运输计划
        TransportPlanCv existingPlan = transportPlanMapper.selectById(transportPlanCv.getId());
        if (existingPlan == null) {
             msg.fail("运输计划不存在");
            return msg;
        }

        // 状态校验（假设只有待执行状态可修改）
        if (existingPlan.getState() != 0) {
             msg.fail("当前状态不允许修改");
            return msg;
        }
        transportPlanMapper.update(null,new UpdateWrapper<TransportPlanCv>()
                .set("consignor_name",transportPlanCv.getConsignorName())
                .set("batch_number",transportPlanCv.getBatchNumber())
                .set("plan_count",transportPlanCv.getPlanCount())
                .eq("id",transportPlanCv.getId()));
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_ADD);
//        ope.setOperationId(empVo.getId());
        String uuid = RandomHelper.uuid();
        ope.setSourceId(uuid);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setOperateType(OperateRecord.OPE_ADD);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        ope.setOperationName(empVo.getEmpNm());
        operateRecordMapper.insert(ope);
        msg.success("修改成功");
        return  msg ;
    }

    @Override
    public ResponseMsg<Object> delete(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        TransportPlanCv department = transportPlanMapper.selectById(id);
        if (department == null) {
            msg.fail("删除失败,计划未找到");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        transportPlanMapper.update(null,new UpdateWrapper<TransportPlanCv>().set("is_deleted",-1).eq("id",department.getId()));
        msg.success("删除成功");
        return msg;
    }

    /**
     * 获取运输计划编号
     * @return
     */
    public static String getTransportPlanCode(){
        return "YSJH"+getDateTime()+getRandom();
    }

    /**
     * 生成时间戳
     */
    private static String getDateTime() {
        DateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        return sdf.format(new Date());
    }

    /**
     * 随机数
     */
    public static String getRandom() {
        int rs = (int) ((Math.random() * 999 + 1) * Math.pow(10, 1 - 1));
        return String.valueOf(rs);
    }
}
